<template>
  <s-layout title="分类" tabbar="/pages/index/category" :bgStyle="{ color: '#fff' }">
    <view class="s-category">
      <view class="newhead" v-if="state.categoryList.style == 'second_two'">
        <s-search-block  :data="state.searchdata" :radius="80" :navbar="false" placeholder="请输入商品" lei="1" @sclick="sclick" />
        <scroll-view scroll-x class="snav">
          <!-- <view class="sitem">
              <view class="sitemview">
                <image class="sitemimg" src="/static/activity-left.png" />
               <text>常购清单</text>
              </view>
            </view> -->
            <view class="sitem" :class="[{ 'menu-item-actives': index == state.activeMenutwo }]"  v-for="(item, index) in state.categoryList?.children"
            :key="item.id" @tap="onMenutwo(index,item)">
              <view class="sitemview">
                <image class="sitemimg" :src="sheep.$url.cdn(item.image)" />
               <text>{{ item.name }}</text>
              </view>
            </view>
          </scroll-view>
        <!-- <u-input v-model="state.value" type="text" :border="true" /> -->
      </view>
      <view class="three-level-wrap ss-flex ss-col-top" :style="[{ height: pageHeight + 'px' }]">
        <scroll-view class="side-menu-wrap" scroll-y :style="[{ height: pageHeight + 'px' }]" v-if="state.categoryList.style != 'second_two'">
          <view
            class="menu-item ss-flex"
            v-for="(item, index) in state.categoryList?.children"
            :key="item.id"
            :class="[{ 'menu-item-active': index == state.activeMenu }]"
            @tap="onMenu(index)"
          >
            <view class="menu-title ss-line-1">
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
        <scroll-view class="side-menu-wrap" scroll-y :style="[{ height: pageHeight + 'px' }]" v-if="state.categoryList.style == 'second_two'">
          <view
            class="menu-item ss-flex"
            v-for="(item, index) in state.categoryListtwo"
            :key="item.id"
            :class="[{ 'menu-item-active': index == state.activeMenu }]"
            @tap="onMenu(index)"
          >
            <view class="menu-title ss-line-1">
              {{ item.name }}
            </view>
          </view>
        </scroll-view>
        <!-- @scrolltolower="loadmore"
           @scrolltoupper="scrolltoupper"
            @scroll="onScroll" -->
        <scroll-view
          class="goods-list-box"
          scroll-y
          :style="[{ height: pageHeight + 'px' }]"
          v-if="state.categoryList?.children?.length"
           
        >
          <image
            v-if="state.categoryList&&state.categoryList.style != 'second_two'"
            class="banner-img"
            :src="sheep.$url.cdn(state.categoryList.children[state.activeMenu].image)"
            mode="widthFix"
          >
          </image>
          <first-one
            v-if="state.categoryList.style === 'first_one'"
            :data="state.categoryList"
            :activeMenu="state.activeMenu"
            :pagination="state.pagination"
          />
          <first-two
            v-if="state.categoryList.style === 'first_two'"
            :data="state.categoryList"
            :activeMenu="state.activeMenu"
            :pagination="state.pagination"
          />
          <second-one
            v-if="state.categoryList.style === 'second_one'"
            :data="state.categoryList"
            :activeMenu="state.activeMenu"
            :pagination="state.pagination"
          />
          <third-one
            v-if="state.categoryList.style === 'third_one'"
            :data="state.categoryList"
            :activeMenu="state.activeMenu"
            :pagination="state.pagination"
          />
          <four-one
            v-if="state.categoryList.style === 'second_two'"
            :data="state.categoryList"
            :activeMenu="state.activeMenu"
            :pagination="state.pagination"
          />
          
          <uni-load-more
            v-if="
              (state.categoryList.style === 'first_one' ||
                state.categoryList.style === 'first_two') &&
              state.pagination.total > 0
            "
            :status="state.loadStatus"
            :content-text="{
              contentdown: '点击查看更多',
            }"
            @tap="loadmore"
          />
        </scroll-view>
      </view>

      
    </view>
    <!-- <s-select-sku
        :goodsInfo="state.goodsInfo"
        :show="state.showSelectSku"
        @addCart="onAddCart"
        @buy="onBuy"
        @change="onSkuChange"
        @close="state.showSelectSku = false"
      /> -->
  </s-layout>
</template>

<script setup>
  import secondOne from './components/second-one.vue';
  import thirdOne from './components/third-one.vue';
  import firstOne from './components/first-one.vue';
  import firstTwo from './components/first-two.vue';
  import fourOne from './components/four-one.vue';
  import sheep from '@/sheep';

  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import { computed, reactive } from 'vue';
  import _ from 'lodash';
  const state = reactive({
    categoryList: [],
    categoryListtwo:[],
    activeMenu: '0',
    activeMenutwo:'0',
    pagination: {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
    },
    loadStatus: '',
    value:'',
    keywords:'',
    searchdata:{
      borderRadius:100,
      keywords:[],
      placeholder:'商品搜索',
      flex:0.5
    },
    isshanghua:false,//是否上滑
    lastScrollTop: 0, // 记录上一次的滚动位置
    // showSelectSku:true,
    // goodsInfo:{}
  });
  

  const { screenHeight, safeAreaInsets, screenWidth, safeArea } = sheep.$platform.device;
  var pageHeight = computed(() => safeArea.height - 44 - 50);

  async function getList(options) {
	  if(options.menu_id){
		    state.activeMenutwo = options.menu_id;
	  }
    const { code, data } = await sheep.$api.category.list({
      id: options.id,
    });
    if (code === 1) {
      state.categoryList = data;
      // console.log( state.categoryList )
      if(state.categoryList.style == 'second_two'){
        pageHeight = pageHeight.value - 120
      }
	  
      state.categoryListtwo = state.categoryList.children[0].children
      if(options.menu_id){
        state.categoryListtwo = state.categoryList.children[options.menu_id].children
      }else{
        state.categoryListtwo = state.categoryList.children[0].children
      }
      getGoodsList(state.categoryList.children[state.activeMenutwo].children[0].id);
      // console.log("163行")
      // console.log(state.categoryList.children)
      // console.log(state.categoryListtwo)
    }
  }

  function onScroll(event) {
    // const currentScrollTop = event.detail.scrollTop;
    // console.log(state.lastScrollTop)
    // if (currentScrollTop > state.lastScrollTop) {
    //   // 当前滚动位置大于上一次滚动位置，表示正在上滑
    //   console.log('正在上滑');
    //   state.isshanghua = true
    // } else {
    //   // 当前滚动位置小于或等于上一次滚动位置，表示不是上滑
    //   console.log('不是上滑');
    //   state.isshanghua = false
    // }
    // console.log(currentScrollTop)
    // state.lastScrollTop = currentScrollTop; // 更新lastScrollTop
  }
  const onMenu = (val) => {
    state.activeMenu = val;
	// console.log(state.categoryList.style)
    if (state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two'|| state.categoryList.style == 'second_two') {
      state.pagination = {
        data: [],
        current_page: 1,
        total: 1,
        last_page: 1,
      };
	
      getGoodsList(state.categoryList.children[state.activeMenutwo].children[val].id);
    }
  };
  function showpop(e){
    console.log(e)
    state.goodsInfo = e
    state.showSelectSku = true
  }
  // 添加购物车
  function onAddCart(e) {
    sheep.$store('cart').add(e);
    state.showSelectSku = false
  }
   // 立即购买
   function onBuy(e) {
    sheep.$router.go('/pages/order/confirm', {
      data: JSON.stringify({
        order_type: 'goods',
        goods_list: [
          {
            goods_id: e.goods_id,
            goods_num: e.goods_num,
            goods_sku_price_id: e.id,
          },
        ],
      }),
    });
    state.showSelectSku = false
  }
  // 规格变更
  function onSkuChange(e) {
    state.selectedSkuPrice = e;
  }

  const onMenutwo = (val,item) => {
    state.activeMenutwo = val;
    state.activeMenu = 0
    state.categoryListtwo = item.children
    // console.log(state.categoryListtwo)
      state.pagination = {
        data: [],
        current_page: 1,
        total: 1,
        last_page: 1,
      };
      console.log(item)
	  getGoodsList(item.children[0].id);
  };
  

  async function getGoodsList(id, page = 1, list_rows = 10) {
    state.loadStatus = 'loading';
	
    const res = await sheep.$api.goods.list({
      category_id: id,
      list_rows,
      page,
      keywords:state.keywords
    });

    if (res.code === 1) {
      // console.log("+208行")
      // console.log(res.data.data)
      let couponList = _.concat(state.pagination.data, res.data.data);
      state.pagination = {
        ...res.data,
        data: couponList,
      };
      if (state.pagination.current_page < state.pagination.last_page) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    }
	  	
  }
  // 加载更多
  function loadmore() {
    console.log(state.loadStatus)
    console.log(state.categoryListtwo)
    if (state.loadStatus !== 'noMore') {
		// console.log(state.categoryList.children[state.activeMenutwo].children[state.activeMenu].id);
		// state.categoryList.children[state.activeMenu].id,
		
		if(state.categoryList.children[state.activeMenutwo].children[state.activeMenu].id){
			getGoodsList(
			
					state.categoryList.children[state.activeMenutwo].children[state.activeMenu].id,
			  state.pagination.current_page + 1,
			);
		}else{
			getGoodsList(
				state.categoryList.children[state.activeMenu].id,
			  state.pagination.current_page + 1,
			);

		}
  
    }else{
      // if(state.activeMenu >= Number(state.categoryListtwo.length)-Number(1)){

      // }else{
      //   //加载下一个分类
      //   state.activeMenu ++ 

      //   if (state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two'|| state.categoryList.style == 'second_two') {
      //     state.pagination = {
      //       data: [],
      //       current_page: 1,
      //       total: 1,
      //       last_page: 1,
      //     };
      
      //     // console.log(state.categoryListtwo[state.activeMenu].id)
      //     getGoodsList(state.categoryListtwo[state.activeMenu].id);
      //   }
      // }
    }
  }
  function scrolltoupper(){
    console.log("到顶部了")
    let oneid = state.categoryListtwo[0].id
    // if(state.activeMenu!=0&&!state.isshanghua&&state.lastScrollTop<=10){
      
    //   //加载下一个分类
    //   state.activeMenu --
    //   // console.log(state.activeMenu)

    //   // state.activeMenu = val;

    //   if (state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two'|| state.categoryList.style == 'second_two') {
    //     state.pagination = {
    //       data: [],
    //       current_page: 1,
    //       total: 1,
    //       last_page: 1,
    //     };

    //     // console.log(state.categoryListtwo[state.activeMenu].id)
    //     getGoodsList(state.categoryListtwo[state.activeMenu].id);
    //   }
    // }
    
  }
  function sclick(e){
    state.keywords = e
    state.pagination = {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
    };
    getGoodsList(state.categoryList.children[state.activeMenu].id);
    
  }
  onLoad(async (options) => {
    // console.log(options)
    await getList(options);
    // if (state.categoryList.style === 'first_one' || state.categoryList.style === 'first_two'|| state.categoryList.style === 'second_two') {
	  // 	  getGoodsList(state.categoryList.children[0].id);

    // }
  });
  onReachBottom(() => {
    loadmore();
  });
</script>

<style lang="scss" scoped>
  .s-category {
    :deep() {
      .side-menu-wrap {
        width: 170rpx;
        height: 100%;
        padding-left: 12rpx;
        background-color: #f6f6f6;
        z-index: 1;
        position: relative;

        .menu-item {
          width: 100%;
          height: 88rpx;
          position: relative;
          transition: all linear 0.2s;

          .menu-title {
            line-height: 32rpx;
            font-size: 30rpx;
            font-weight: 400;
            color: #333;
            margin-left: 28rpx;
            position: relative;
            z-index: 0;

            &::before {
              content: '';
              width: 64rpx;
              height: 12rpx;
              background: linear-gradient(
                90deg,
                var(--ui-BG-Main-gradient),
                var(--ui-BG-Main-light)
              ) !important;
              position: absolute;
              left: -64rpx;
              bottom: 0;
              z-index: -1;
              transition: all linear 0.2s;
            }
          }

          &.menu-item-active {
            background-color: #fff;
            border-radius: 20rpx 0 0 20rpx;

            &::before {
              content: '';
              position: absolute;
              right: 0;
              bottom: -20rpx;
              width: 20rpx;
              height: 20rpx;
              background: radial-gradient(circle at 0 100%, transparent 20rpx, #fff 0);
            }

            &::after {
              content: '';
              position: absolute;
              top: -20rpx;
              right: 0;
              width: 20rpx;
              height: 20rpx;
              background: radial-gradient(circle at 0% 0%, transparent 20rpx, #fff 0);
            }

            .menu-title {
              font-weight: 600;

              &::before {
                left: 0;
              }
            }
          }
        }
      }

      .goods-list-box {
        background-color: #fff;
        width: calc(100vw - 100px);
        padding: 10px;
        position: relative;
        z-index: 10;
      }

      .banner-img {
        width: calc(100vw - 130px);
        border-radius: 5px;
        margin-bottom: 20rpx;
      }
    }
  }
  .newhead{
    background-color: #fff;
    height: 240rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    .snav{
      height: 100rpx;
      border-bottom: 1rpx solid #eee;
      flex: 2;
      white-space: nowrap;
      margin-top: 13rpx;
      padding-left: 20rpx;
      position: relative;
      z-index: 1;
    }
    .sitem{
      display: inline-block;
      width: 18%;
      padding: 0 auto;
      margin-right: 10rpx;
      .sitemimg{
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        margin-bottom: 20rpx;

      }
      .sitemview{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 6rpx;
      }
      text{
        color: #333;
        font-weight: 500;
        font-size: 28rpx;

      }
    }
  }
  .menu-item-actives{
    background: linear-gradient(90deg, var(--ui-BG-Main-gradient), var(--ui-BG-Main-light)) !important;
    // border: 1rpx solid ;
    border-radius: 20rpx;
    text{
      // color: #fff !important;
    }
    
  }
</style>
